import {reqNav,reqGoods} from "../../request/api"
import {createSelector} from "reselect"
//状态
const initState={
    //导航list
    navList:[],
    //商品
    goods:[],
    n:0,//当前被选中的下标
}

//action types
const TYPES={
    HOME_CHANGE_NAV:"HOME_CHANGE_NAV",
    HOME_CHANGE_BANNER:"HOME_CHANGE_BANNER",
    HOME_CHANGE_GOODS:"HOME_CHANGE_GOODS",
    HOME_CHANGE_N:"HOME_CHANGE_N"
}

// action creators 
export const actions={
    //修改导航<list>type:"HOME_CHANGE_NAV",list:[1,2,3]</list>
    changeNavList:(list)=>({type:TYPES.HOME_CHANGE_NAV,list}),
    changeGoodsList:(list)=>({type:TYPES.HOME_CHANGE_GOODS,list}),
    changeN:n=>({type:TYPES.HOME_CHANGE_N,n}),
    //逻辑
    //导航
    reqNav:()=>(dispatch,getState)=>{
        //可以将状态层作为缓存层
        let {navList}=getState().home
        if(navList.length>0){
            return;
        }
        reqNav().then(res=>{
            if(res.code==200){
                //修改navList
                dispatch(actions.changeNavList(res.list))
            }
        })
    },
    //商品
    reqGoods:()=>(dispatch,getState)=>{
        let {goods}=getState().home
        if(goods.length>0){
            return;
        }
        reqGoods().then(res=>{
            res.code===200&&dispatch(actions.changeGoodsList(res.list))
        })
    }
}

// reducer 
const reducer=(state=initState,action)=>{
    switch(action.type){
        //修改导航list
        case TYPES.HOME_CHANGE_NAV:
            return {
                ...state,
                navList:action.list
            }
        //修改GOODS list
        case TYPES.HOME_CHANGE_GOODS:
            return {
                ...state,
                goods:action.list
            }
        //修改n
        case TYPES.HOME_CHANGE_N:
        return {
            ...state,
            n:action.n
        }
        default:
            return state
    }
}

export default reducer
// selector 
export const getNavList=state=>state.home.navList;
export const getGoods=state=>state.home.goods;
export const getN=state=>state.home.n
export const getShowGoods=createSelector(
    [getGoods,getN],
    (goods,n)=>{
        return goods.length>0?goods[n].content:[]
    }
)
